package org.apache.lucene.analysis.kr.demo;

import java.io.File;
import java.util.Date;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.document.Document;

public class Searcher {

	public static void search(File indexDir, String q) throws Exception {
		
		IndexReader reader = IndexReader.open(indexDir); // 색인을 연다
		Analyzer analyzer = new StandardAnalyzer();
		IndexSearcher searcher = new IndexSearcher(reader);
		
		// 질의를 분석함.
		QueryParser parser = new QueryParser("contents", analyzer);
		Query query = parser.parse(q);
		
		long start = new Date().getTime();
		Hits hits = searcher.search(query);
		long end = new Date().getTime();
		
		System.out.println("Found " + hits.length() + 
				" document(s) (in " + (end-start) +
				" milliseconds) that matched query '" + q + "':");
	
		for (int i=0; i<hits.length(); i++) {
			Document doc = hits.doc(i);
			System.out.println(doc.get("filename"));
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		if (args.length != 2) {
			throw new Exception("Usage: java " + Searcher.class.getName()
					+ " <index dir> <query>");
		}

		File indexDir = new File(args[0]);
		String q = args[1];
		
		if  (!indexDir.exists() || !indexDir.isDirectory()) {
			throw new Exception(indexDir + " does not exist or is not a directory.");
		}
		
		search(indexDir, q);
	}

}
